package com.bwie.auth.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.Constants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserReqLogin;
import com.bwie.common.domain.request.UserReqSignUp;
import com.bwie.common.exceptions.BizException;

import java.util.List;
import java.util.Objects;

/**
 * @Author Junchen_N1
 * @Date 2025/6/17 9:18
 * @ClassName RemoteSystemService
 * @Description TODO
 */
public class RemoteSystemService {

    public static final String HOST = "127.0.0.1:9002/user/";

    /**
     * 远程调用system用户名密码查询用户信息
     * @param userReqLogin
     * @return
     */
    public static User selectUserByUsernameAndPassword(UserReqLogin userReqLogin) {
        String jsonResult = HttpUtil.createPost(HOST + "selectUserByUsernameAndPassword").body(JSON.toJSONString(userReqLogin)).
                execute().body();

        return JSON.parseObject(getJsonObject(jsonResult), User.class);
    }

    /**
     * 根据用户id查询用户好友列表
     * @param userId
     * @return
     */
    public static List<User> selectUserFriendsListByUserId(Integer userId){
        String jsonResult = HttpUtil.createGet(HOST + "selectUserFriendsListByUserId?userId=" + userId).execute().body();
        return JSON.parseArray(getJsonObject(jsonResult),User.class);
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    public static User selectUserByUsername(String username){
        String jsonResult = HttpUtil.createGet(HOST + "selectUserByUsername/"+username).execute().body();

        return JSON.parseObject(getJsonObject(jsonResult), User.class);
    }

    /**
     * 根据手机号查询用户信息
     * @param tel
     * @return
     */
    public static User selectUserByTel(String tel){
        String jsonResult = HttpUtil.createGet(HOST + "selectUserByTel/"+tel).execute().body();

        return JSON.parseObject(getJsonObject(jsonResult), User.class);
    }

    /**
     * 解封装
     * @param jsonResult
     * @return
     */
    private static String getJsonObject(String jsonResult) {
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        if (!Objects.equals(String.valueOf(Constants.SUCCESS), String.valueOf(jsonObject.get("code")))) {
            throw new BizException("服务器繁忙，请稍后重试");
        }
        return JSON.toJSONString(jsonObject.get("data"));
    }

    /**
     * 注册
     * @param userReqSignUp
     */
    public static void addUser(UserReqSignUp userReqSignUp) {
        String jsonResult = HttpUtil.createPost(HOST + "addUser").body(JSON.toJSONString(userReqSignUp)).execute().body();
        getJsonObject(jsonResult);
    }
}
